using WeatherSystem.API.Models;

namespace WeatherSystem.API.Extensions
{
    /// <summary>
    /// WeatherDataEntry 和 StatisticsEntry 扩展方法
    /// </summary>
    public static class WeatherDataExtensions
    {
        /// <summary>
        /// 将 WeatherDataEntry 转换为字典
        /// </summary>
        /// <param name="entry">天气数据条目</param>
        /// <returns>字典表示</returns>
        public static Dictionary<string, object> ToDictionary(this WeatherDataEntry entry)
        {
            var result = new Dictionary<string, object>
            {
                ["id"] = entry.Id,
                ["cityId"] = entry.CityId,
                ["cityName"] = entry.City?.Name ?? "",
                ["recordedAt"] = entry.RecordedAt,
                ["source"] = entry.Source ?? "",
                ["createdAt"] = entry.CreatedAt
            };

            foreach (var metric in entry.Metrics)
            {
                result[metric.MetricKey] = ConvertRawValueToTyped(metric.RawValue, metric.DataType);
            }

            return result;
        }

        /// <summary>
        /// 将 StatisticsEntry 转换为字典
        /// </summary>
        /// <param name="entry">统计数据条目</param>
        /// <returns>字典表示</returns>
        public static Dictionary<string, object> ToDictionary(this StatisticsEntry entry)
        {
            var result = new Dictionary<string, object>
            {
                ["id"] = entry.Id,
                ["cityId"] = entry.CityId,
                ["cityName"] = entry.City?.Name ?? "",
                ["statisticType"] = entry.StatisticType,
                ["statisticDate"] = entry.StatisticDate,
                ["dataPointCount"] = entry.DataPointCount,
                ["createdAt"] = entry.CreatedAt,
                ["updatedAt"] = entry.UpdatedAt
            };

            // 添加统计值
            foreach (var value in entry.Values)
            {
                result[$"{value.MetricKey}_{value.AggregationType}"] = ConvertRawValueToTyped(value.RawValue, "decimal");
            }

            return result;
        }

        /// <summary>
        /// 将原始值转换为指定类型
        /// </summary>
        /// <param name="rawValue">原始值</param>
        /// <param name="dataType">数据类型</param>
        /// <returns>转换后的值</returns>
        private static object ConvertRawValueToTyped(string rawValue, string dataType)
        {
            return dataType.ToLower() switch
            {
                "decimal" or "double" or "float" => decimal.TryParse(rawValue, out var decimalValue) ? decimalValue : 0m,
                "int" or "integer" => int.TryParse(rawValue, out var intValue) ? intValue : 0,
                "bool" or "boolean" => bool.TryParse(rawValue, out var boolValue) && boolValue,
                "datetime" or "date" => DateTime.TryParse(rawValue, out var dateValue) ? dateValue : DateTime.MinValue,
                _ => rawValue
            };
        }
    }
}